package com.xinghou.platform.dao.main.aspect;

import org.aspectj.lang.ProceedingJoinPoint;

import com.xinghou.platform.dao.main.common.DBUserLevelCached;
import com.xinghou.platform.model.main.UserGeo;
import com.xinghou.platform.util.JsonUtil;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class UserGeoCacheAspect extends DBUserLevelCached {
	@Pointcut("execution(public * com.xinghou.platform.dao.main.UserGeoDAO.getUserGeoById(..))")
	public void getUserGeoById(){
	}

	@Pointcut("execution(public * com.xinghou.platform.dao.main.UserGeoDAO.updateUserGeo(..))")
	public void updateUserGeo(){
	}

	@Around("getUserGeoById()")
	public UserGeo getUserGeoById(ProceedingJoinPoint pjp) throws Throwable{
		String id = ((Object[])pjp.getArgs())[0].toString();
		String key = String.format(CACHE_USERGEO_GEOID , id);
		Object jsonToken = getRedisClient().get(key, CACHED_DB_INDEX);
		if(jsonToken == null){
			UserGeo userGeo = (UserGeo)pjp.proceed();
			if(userGeo != null)
				getRedisClient().set(key, JsonUtil.toJson(userGeo), CACHED_DB_INDEX);
			return userGeo;
		}else{
			UserGeo userGeo = (UserGeo)JsonUtil.fromJson(jsonToken.toString(), UserGeo.class);
			return userGeo;
		}
	}
	@Around("updateUserGeo()")
	public int updateUserGeo(ProceedingJoinPoint pjp) throws Throwable{
		
		UserGeo userGeo = (UserGeo)((Object[])pjp.getArgs())[0];
		
		int returnno = (int) pjp.proceed();
		
		String keyInfoId = String.format(CACHE_USERGEO_GEOID , userGeo.getGeoId());
		
		if(getRedisClient().exists(keyInfoId, CACHED_DB_INDEX)){
			getRedisClient().set(keyInfoId, JsonUtil.toJson(userGeo), CACHED_DB_INDEX);
		}
		
		return returnno;
	}
	
}
